﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using WPS.Code.Code;
using WPS.Code.Utils;
using WPS.Log;
using WPS.Model;

namespace WPS.Web.Controllers
{
    public class RegisterController : ApiController
    {
        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("weboffice/register")]
        public JsonResult<Response> Register()
        {
            LogHelper.Info("进入weboffice/register");
            try
            {
                string userId = string.Empty;
                string userName = string.Empty;
                WPSUserInfo userInfo = null;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "MS_HttpContext参数为null."));
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["user_id"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "用户名为空."));
                }
                userId = request["user_id"].ToString();
                if (request["user_name"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "姓名为空."));
                }
                userName = request["user_name"].ToString();
                using (WPSModel context = new WPSModel())
                {
                    userInfo = context.WPSUserInfo.Where(u => u.ID == userId).FirstOrDefault();
                    if (userInfo != null)
                    {
                        return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "用户名已存在."));
                    }
                    userInfo = new WPSUserInfo { ID = userId, NAME = userName, PERMISSION = "write", AVATAR_URL = WPSConfig.Default_Avatar };
                    context.WPSUserInfo.Add(userInfo);
                    context.SaveChanges();
                }
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Success, "", "注册成功."));
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, ex.Message));
            }
        }
    }
}
